var base_url = ctx + 'api/bd';

// 部门推荐 -- 承办单位推荐
function handleDeptRecommended(){
    let content = $("#fmContent").val();
    let area = $("#fmAreaName").val();
    let data = {
        "title": "",
        "content": content,
        "dial_area": area
    }
    $.ajax({
        type: 'post',
        data: JSON.stringify(data),
        datatype: 'json',
        contentType: 'application/json;charset=UTF-8',
        async: false,
        url: base_url + '/handleDeptRecommend',
        success: function (result) {
            let value = result.data.pred_topk;
            if (value.length > 0){
                $("#recommendDeptTable").show();
                let options = {
                    data: value,
                    sidePagination: "client",
                    showSearch: false,
                    showRefresh: false,
                    showToggle: false,
                    showColumns: false,
                    pagination: false,
                    onDblClickRow: onDblClickRecommendDept,
                    columns: [
                        {field: 'pred_idx', title: '案件编号', align: 'center'},
                        {field: 'pred_score', title: '相似度值', align: 'center',formatter:function (value){
                                return Number(value * 100).toFixed(1) + "%";
                            }},
                        {field: 'pred_label', title: '承办部门（<span style="color: red">双击选中</span>）主办', align: 'center',formatter:function (value) {
                                return "<span style='color: crimson;' title='双击即可选中该部门'>"+value+"</span>"
                            }}
                    ]
                };
                $.table.init(options);
            }
        }
    });
}

function onDblClickRecommendDept(row, $element){
    let value = row.pred_label;
    if (value.length >0){
        let data = {
            "deptName": value
        }
        $.ajax({
            type: 'post',
            data: data,
            dataType: 'json',
            async: false,
            url: base_url + '/selectRecommendDeptNo',
            success: function (result) {
                $("input[name='sbdeptName']").val(value);
                $("input[name='sbdeptId']").val(result.data);
                let desc = $("#sendDesc").val();
                if (desc.indexOf("XXX") > 0 || desc.length > 0){
                    $("#sendDesc").val("请 "+value+" 调查处理后直接与来话人联系，并将处理结果抄复我办。请注意来话人个人信息保密。")
                }
            }
        });
    }
}

// 内容类别推荐
function contentTypeRecommend(content){
    let data = {
        "logid": "",
        "topn": 5, //5个最推荐的
        "texts": [content]
    }
    $.ajax({
        type: "POST",
        url: base_url + "/contentTypeRecommend",
        data: JSON.stringify(data),
        datatype: 'json',
        contentType: 'application/json;charset=UTF-8',
        async: false,
        error: function (res) {
            $.modal.alertError(res.message);
        },
        success: function (res) {
            let tags = res.data.results[0].tags; // 对象数组
            if (tags.length > 0){
                $("#contentType").show();
                var options = {
                    data: tags,
                    sidePagination: "client",
                    showSearch: false,
                    showRefresh: false,
                    showToggle: false,
                    showColumns: false,
                    pagination: false,
                    onDblClickRow: onDblClickContentType,
                    columns: [
                        {field: 'score', title: '推荐率',formatter:function (value){
                                return Number(value * 100).toFixed(1) + "%";
                            }},
                        {field: 'normalize_tag', title: '推荐内容类别（<span style="color: red">双击选中</span>）',formatter:function (value){
                                return "<span style='color: #6486ed;' title='双击即可选中该类别'>"+value+"</span>";
                            }}
                    ]
                }
                $.table.init(options);
            }
        }
    });
}

// 选中推荐的内容类别
function onDblClickContentType(row, $element){
    let value = row.normalize_tag;
    let param = {
        "types" : value
    }
    if (value.length > 0){
        $.ajax({
            type: 'post',
            data: param,
            dataType: 'json',
            url: base_url + '/selectContentTypeNo',
            success: function (result) {
                let data = result.data;
                $('#qxCT').combobox('setText', data.sortname);
                $("input[name='dcntAname']").val(data.sortname);
                $("input[name='dcntAcode']").val(data.codepk);
            }
        });
    }
}

// 关键词/热词提取
function getHotWord(content){
    content = content.replace(/[\r\n]/g, '');
    let data =  {
        "letter": content
    }
    $.ajax({
        type: "POST",
        url: base_url + "/getHotWord",
        data: JSON.stringify(data),
        datatype: 'json',
        contentType: 'application/json;charset=UTF-8',
        async: false,
        error: function (res) {
            $.modal.alertError("系统错误");
        },
        success: function (res) {
            let data = res.data.data;
            for (let i = 0; i < data.length; i++) {
                $('.antistop').tagsinput('add', data[i].hot_word)
            }
        }
    });
}

// 智能纠错
function checkError(){
    var text = $('#fmContent').val();
    let reg = /([=,.?!@#$%^&*()_+:"<>/\[\]\\`~—，。、《》？；’：“【】、{}|·！￥…（）-])$/g;
    if (reg.test(text)) {
        let testList = text.split('\n');
        var parameter = testList[testList.length - 1]; //每次检测最后一句话
        if (parameter.length > 0) {
            let data = {
                    "action":"text_correction",
                    "data":[
                        {
                            "content": parameter
                        }],
                    "user_id": "002",
                    "system": "Unix",
                    "web_version": "v1.0",
                    "source":"word",
                    "type": 1
                }
            $.ajax({
                type: "post",
                url: base_url + "/errorCorrection",
                data: JSON.stringify(data),
                datatype: 'json',
                contentType: 'application/json;charset=UTF-8',
                success: function (res) {
                    if (res.data.message === 'success'){
                        let err_num = res.data.result.error_num;
                        if (err_num > 0){
                            let details = res.data.result.output[0].details;
                            for (let i = details.length - 1; i >= 0; i--) {
                                let fragments = details[i].fragments
                                if (fragments.length > 0){
                                    for (let j = 0; j < fragments.length; j++) {
                                        let explain = fragments[j].explain;
                                        let errText = fragments[j].frag_ori;
                                        let sureText = fragments[j].frag_fixed;
                                        let errHtml = '<div><div>检测到错别字（<span style="color: red;">点击确认自动修改</span>）</div><hr style=\'margin: 10px 0 10px 0;\'>修改建议：<div style=\'margin: 10px;\' id=\'rightText\'><span style="color: #6486ed">'+explain+'</span></div></div>';
                                        $.modal.confirm( errHtml , function() {
                                            let rightText = text.replace(parameter,parameter.replace(errText,sureText))
                                            $('#fmContent').val(rightText).focus()
                                        });
                                    }
                                }
                            }
                        }
                    }
                },
                error: function (res){
                    $.modal.errormsg(res.message)
                }
            });
        }
        return false;
    }
}

//事发地址推荐
if($("#fmAddress")[0]) {
    $("#fmAddress").typeahead({
        source: function (query, process) {
            if (/^[\u4e00-\u9fa5]{2,}$/.test(query)){
                let param = {
                    "address" : $("#fmAddress").val() == null ? query : $("#fmAddress").val()
                };
                $.ajax({
                    url: base_url + "/addressSearch",
                    data: param,
                    type: "get",
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    timeout: 50000,
                    async: false,
                    success: function (res) {
                        let array = [];
                        if (res.data == null){
                            return false
                        }
                        let data = res.data.result.data;
                        for (let i = 0; i < data.length; i++) {
                            let item = {
                                "id" : data[i].uid,
                                "name": data[i].address,
                            }
                            array.push(item)
                        }
                        process(array);
                    },
                    error: function (msg){
                        console.log(msg.message)
                    }
                })
            }else{
                return false;
            }
        },
        displayText:function(item){
            return item.name;
        },
        minLength: 2,
        delay: 1
    });
}
